# customer/adminx.py

import xadmin

from .models import ContractList,PayNode
from django.utils.safestring import mark_safe 
from xadmin import views
from django.db.models import Q,F

class ContractListAdmin(object):
    list_display = ['name','type','project_col','pay_type','pay_num','in_or_out','pay_total','isdone','isback','by_year','handler','back_time','desc']
    search_fields = ['name','addproject__tempname','addproject__company__fullname']
    list_filter = ['isdone','isback','back_time']
    list_editable = ['type','pay_type','pay_num','in_or_out','pay_total','isdone','isback','by_year','submit_status','accept_status','accept_by']
    ordering = ['-back_time']
    # def save_models(self):
    #     self.new_obj.operator = self.request.user
    #     super().save_models()

xadmin.site.register(ContractList,ContractListAdmin)

class PayNodeAdmin(object):
    list_display = ['contract','in_or_out','pay_total','pay_time','handler','desc']
    search_fields = []
    list_filter = []
    exclude = []
    def save_models(self):
        obj = self.new_obj
        obj.save()
        ContractList.objects.filter(id=obj.contract.id).update(pay_total=F('pay_total')+obj.pay_total)


    def delete_model(self):
        '''
        此方法只能在单独的添加、删除页面，不能在action中进行修改更新。
        如果要更新，则要用到信号机制。
        '''
        ContractList.objects.filter(id=self.obj.contract.id).update(pay_total=F('pay_total')-self.obj.pay_total)
        super(PayNodeAdmin,self).delete_model()

        # super().save_models()
    # def save_models(self):
    #     self.new_obj.add_by = self.request.user
    #     super().save_models()
    # def save_models(self):
    #     self.new_obj.add_by = self.request.user
    #     # self.new_obj.save()
    #     super().save_models()

    # def get_readonly_fields(self):
    #     """  重新定义此函数，限制普通用户所能修改的字段  """
    #     if self.user.is_superuser:
    #         self.readonly_fields = []
    #     return self.readonly_fields
    # readonly_fields = ('add_by',)
xadmin.site.register(PayNode,PayNodeAdmin)

